<?php
class ome_ctl_admin_return extends desktop_controller{
    var $name = "售后服务";
    var $workground = "aftersale_center";

    function index(){
        $params = array(
            'title'=>'售后服务',
            'use_buildin_new_dialog' => false,
            'use_buildin_set_tag'=>false,
            'use_buildin_recycle'=>false,
            'use_buildin_export'=>false,
            'use_buildin_import'=>false,
            'use_buildin_filter'=>true,
            'actions' =>array(
              array(
                'label' => '新建售后服务',
                'href' => 'index.php?app=ome&ctl=admin_return&act=add_return',
                'target' => "dialog::{width:700,height:400,title:'新建售后服务'}",
              )
            ),
            );
        if ($_GET['status'])
        {
            $params['base_filter']['status'] = $_GET['status'];
        }
        $this->finder('ome_mdl_return_product',$params);
     }

     /*
     *对当前售后申请各状态进行保存
     */
     function save(){

        $oProduct = &$this->app->model('return_product');
        $oOrder = &$this->app->model('orders');

        $this->begin("javascript:finderGroup['".$_GET['finder_id']."'].refresh();");
        $return_id = $_POST['return_id'];
        $status = $_POST['status'];
        $bn = $_POST['bn'];
        $bn_array = array();
        $oPro_detail=$oProduct->dump($return_id,'status,order_id');
        $order_detail = $oOrder->dump($oPro_detail['order_id'], 'ship_status');

        //判断订单是否已经全部退货
        if ($order_detail['ship_status'] == '4'){
            $this->end(false, app::get('base')->_('订单已全部退货,请拒绝此售后申请!'));
        }

        //增加售后服务保存状态前的扩展
        foreach(kernel::servicelist('ome.aftersale') as $o){
            if(method_exists($o,'pre_save_status')){
                $o->pre_save_status($_POST);
            }
        }

        if($status==2 || $status==3){
            $adata = $_POST;
            if(empty($bn)){
                $this->end(false, app::get('base')->_('对不起,您没有可申请的商品'));
            }else{
                foreach($adata['bn'] as $key => $val){
                    if(!isset($bn_array[$key])){
                        $bn_array[$key] =$key;
                        if($status==3 && $adata['bn'][$key]<=0){
                            $this->end(false,app::get('base')->_('货号为'.$key.'必须大于0'));
                        }
                        if($adata['bn'][$key]>$adata['effective'][$key]){
                            $this->end(false,app::get('base')->_('货号为'.$key.'大于可申请量'));
                        }
                    }
                }
            }
            $oProduct->tosave($adata,$bn_array);
        }else if(($status==4 || $status==8) && $oPro_detail['status']!=8){
                $data=$_POST;
                 /*统计此次请求对应货号退货数量累加*/
                $ret=array();
                $can_refund=array();
                foreach($data['bn'] as $k=>$v){
                    if($_POST['deal'.$k] == 1 || $_POST['deal'.$k]==2){
                        if(isset($ret[$v])){
                            $can_refund[$v][num]++;
                        }else{
                            $ret[$v] = $v;
                            $can_refund[$v]['num']=1;
                            $can_refund[$v]['effective']=$data['effective'][$k];
                        }
                        if($can_refund[$v]['effective']==0){

                            $this->end(false, app::get('base')->_('货号为['.$v.']没有可申请量，请选择拒绝操作'));

                        }else if($can_refund[$v]['num']>$can_refund[$v]['effective']){

                            $this->end(false,app::get('base')->_('货号为['.$v.']大于可申请量，请选择拒绝操作'));
                        }
                    }
                }
               $oProduct->saveinfo($data);

        }else{
               $data = array('return_id'=>$return_id,'status'=>$_POST['status'],'last_modified'=>time());
               $oProduct->update_status($data);
        }

        //增加售后服务保存状态后的扩展
        foreach(kernel::servicelist('ome.aftersale') as $o){
            if(method_exists($o,'after_save_status')){
                $o->after_save_status($_POST);
            }
        }

        $this->end(true, app::get('base')->_('操作成功'));


     }

     /*
      * 新建售后服务 add_return
      */
     function add_return(){

         if ($_POST['doSubmit']=='do'){

             $oOrders = &$this->app->model('orders');
             $order_bn = preg_replace("/[\s]*/i","",$_POST['order_bn']);
             $order_bn = addslashes($order_bn);
             $exactitude = $_POST['exactitude'];
             if (!$exactitude){
                 $filter = " `order_bn` like '".$order_bn."%' ";
                 $exactitude = 'false';
                 $limit = 100;
             }
             else{
                 $filter = " `order_bn`='".$order_bn."' ";
                 $limit = 1;
             }
             $orders = $oOrders->getOrderBybn($filter, 'order_bn,order_id,ship_status', 0, $limit);
             $this->pagedata['orders'] = $orders;
             $this->pagedata['search_flag'] = 'true';
             $this->pagedata['keywords'] = $order_bn;
             $this->pagedata['exactitude'] = $exactitude;

         }

         $this->display("admin/return_product/add_return.html");
     }

  /*
    *售后服务申请
    */
    function apply($order_id){
        $order_id = intval($order_id);
        if (!$order_id) die('订单传入错误');
        $oOrders_item = &$this->app->model('order_items');
        $oReturn_item = &$this->app->model('return_process_items');
         $oProduct = &$this->app->model('return_product');
        $items= $oOrders_item->getList('*',array('order_id'=>$order_id));
        foreach($items as $k=>$v){
            $refund = $oReturn_item->Get_refund_count($order_id,$v['bn']);
            $items[$k]['effective']=$refund;
            $items[$k]['branch']=$oReturn_item->getBranchCodeByBnAndOd($v['bn'],$order_id);
        }

        //获取仓库模式
        $branch_mode = &app::get('ome')->getConf('ome.branch.mode');
        $this->pagedata['branch_mode'] = $branch_mode;

        $this->pagedata['items']=$items;
        $this->pagedata['order_id']=$order_id;

        $this->display("admin/return_product/return_apply.html");
    }

    /* 售后申请*/
    function apply_add(){
        //$url = $_POST['url'];
        //$this->begin($url);
        $autohide = array("autohide"=>5000);
        $oProduct = &$this->app->model('return_product');
        $oItems = &$this->app->model('return_product_items');
        $oOrder = &$this->app->model('orders');
        $order_id = $_POST['order_id'];
        $order = $oOrder->dump($order_id,'member_id');

        $delivery_id=$_POST['delivery_id'];
        $title = $_POST['title'];
        if($title==''){
           //$this->end(false,'售后标题不可为空',$url,$autohide);
           echo "<script>parent.MessageBox.success('售后标题不可为空!');</script>";
           exit;
        }else if(empty($_POST['goods_bn']))
        {
//            $this->end(false,'您没有选择商品',$url,$autohide);
            echo "<script>parent.MessageBox.success('您没有选择商品!');</script>";
            exit;
        }else if($delivery_id=='')
        {
//            $this->end(false,'请为此售后服务选择收货人信息',$url,$autohide);
            echo "<script>parent.MessageBox.success('请为此售后服务选择收货人信息!');</script>";
            exit;
        }
        $items = array();
        foreach($_POST['goods_bn'] as $key => $val){
            $item = array();
            $item['bn'] = $val;
            $item['name'] = $_POST['goods_name'][$val];
            $item['product_id'] = $_POST['product_id'][$val];
            $item['num'] = intval($_POST['num'][$val]);
			if($_POST['num'][$val] <= 0){
				echo "<script>parent.MessageBox.success('申请数量不可以为小于1的整数');</script>";
                 exit;
			}
            if($_POST['effective'][$val]<=0){
//                 $this->end(false,'剩余数量不足不可以操作',$url,$autohide);
                 echo "<script>parent.MessageBox.success('剩余数量不足不可以操作');</script>";
                 exit;
            }
            else if($_POST['num'][$val]>$_POST['effective'][$val])
            {
//                $this->end(false,'申请数量不可以大于剩余数量',$url,$autohide);
                echo "<script>parent.MessageBox.success('申请数量不可以大于剩余数量');</script>";
                exit;
            }
            $val = str_replace(" ","_",$val);
            $branch_id = $_POST['branch_id'.$val];
            $branch_num=$oProduct->Get_delivery($branch_id,$val,$order_id);
            if($_POST['num'][$val]>$branch_num){
//                $this->end(false,'所选仓库数量不足',$url,$autohide);
                echo "<script>parent.MessageBox.success('所选仓库数量不足');</script>";
                 exit;
            }
            $item['branch_id']=$branch_id;
            $items[]=$item;
       }
       $upload_file = "";
        if( $_FILES['attachment']['size'] > 314572800 )
        {
//            $this->end(false,'上传文件不能超过300M',$url,$autohide);
            echo "<script>parent.MessageBox.success('上传文件不能超过300M');</script>";
            exit;
        }
        $type=array("jpg","gif","bmp","jpeg","rar","zip");
        if ($_FILES['attachment']['name'])
        if(!in_array(strtolower($this->fileext($_FILES['attachment']['name'])),$type)){
            $text=implode(",",$type);
//            $this->end(false,'您只能上传以下类型文件:'.$text,$url,$autohide);
            echo "<script>parent.MessageBox.success('您只能上传以下类型文件:$text');</script>";
            exit;
        }
        $ss = kernel::single('base_storager');
        $id = $ss->save_upload($_FILES['attachment'],"file","",$msg);//返回file_id;
        $upload_file = $id;

        /*if( $_FILES['attachment']['name'] != "" ){

            /*$file_type = strtolower($this->fileext($_FILES['attachment']['name']));
            $file_path = "upload/return/";
            $file_name = time().rand(0,15);
            $upload_file = $file_path.$file_name.".".$file_type;
            if(move_uploaded_file($_FILES['attachment']['tmp_name'],$upload_file)){
                $upload_file = kernel::base_url(1).'/'.$upload_file;
            }
            echo "<script>parent.MessageBox.success('您只能上传以下类型文件:'.$upload_file.'');</script>";

        }*/
        $aData['order_id'] = $order_id;

        $aData['title'] = $_POST['title'];
        $aData['add_time'] = time();
        $aData['attachment'] = $upload_file;
        $aData['member_id'] = $order['member_id'];//申请人
        $aData['content'] = $_POST['content'];
        $aData['status'] = 1;

        $opInfo = kernel::single('ome_func')->getDesktopUser();
        $aData['op_id'] = $opInfo['op_id'];

        $aData['delivery_id'] = $_POST['delivery_id'];
        $return_bn =  $oProduct->gen_id();
        $aData['return_bn'] = $return_bn;
        $oProduct->save($aData);
        foreach($items as $k=>$v){
            $v['return_id'] = $aData['return_id'];
            $oItems->save($v);
        }
        $oOperation_log = &$this->app->model('operation_log');
        $memo = '创建售后服务';
        $oOperation_log->write_log('return@ome',$aData['return_id'],$memo);

        //售后申请 API
        foreach(kernel::servicelist('service.aftersale') as $object=>$instance){
            if(method_exists($instance,'add_aftersale')){
                $instance->add_aftersale($aData['return_id']);
            }
        }

        $finder_id = $_GET['finder_id'];
        echo "<script>parent.finderGroup['$finder_id'].refresh.delay(400,parent.finderGroup['$finder_id']);";
        echo "parent.MessageBox.success('售后服务申请成功');parent.$('return-apply').getParent('.dialog').retrieve('instance').close();</script>";

    }

    function fileext($filename){
        return substr(strrchr($filename, '.'), 1);
    }
    function check()
    {
        $branch_id = $_GET['branch_id'];
        $bn = $_GET['bn'];
        $order_id = $_GET['order_id'];
        $oProduct = &$this->app->model('return_product');
        $result=$oProduct->Get_delivery($branch_id,$bn,$order_id);

        echo json_encode($result);
    }

    function file_download2($return_id){
        $oProduct = &$this->app->model('return_product');
        $info = $oProduct->dump($return_id);
        $filename = $info['attachment'];
        if (is_numeric($filename)){
            $ss = kernel::single('base_storager');
            $a = $ss->getUrl($filename,"file");
            $oProduct->file_download($a);
        }else{
            header('Location:'.$filename);
        }

    }


}
?>
